
var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var reload = true;
var buy_hasMore = true;
var buy_loadingMore = false;
var sell_hasMore = true;
var sell_loadingMore = false;

var page = 1;
var tc = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    tc: 0,

    buy_orders: [],
    hasBuyData:true,
    sell_orders: [],
    hasSellData: true,
    uid:0,
    token:'',
    openid:'',
    canEdit: 0,
    
    isIphone_x: false,
    nav_bgColor: '#ffffff',
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tc = app.get_tc();
    var titlename = util.orgid == '12545' ? tc == 1 ? '訂單' : 'order' : tc == 1 ? '訂單' : '订单';
    wx.setNavigationBarTitle({
      title: titlename,
    })
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    })
    page = 1;
    var that = this;
    tc = app.get_tc();
    that.setData({
      tc: tc
    })
    if(tc == 1){
      titlename = '訂單';
    }
    wx.setNavigationBarTitle({
      title: titlename,
    });


    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    wx.getSystemInfo({
      success: function(res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
        });
      }
    });
    
    reload = true;
    //当前登录用户信息
    app.getLoginUserInfo(function (res) {
      if (res == -1) {//用户拒绝授权
        wx.hideLoading();
        
        return;
      }
      //更新数据
      that.setData({
        uid: res.uid,
        token: res.token,
        openid: res.openid
      });

      that.getZongOrderList(2, 1, 20, true);
      
    });
  },

  loadMore: function (e) {
    
    if (buy_hasMore && !buy_loadingMore) {
        buy_loadingMore = true;
        page++;
        this.getZongOrderList(2, page, 20, false);
      } else {
        console.log("没有更多了");
      }
    
  },


  //获取订单 列表  type: 1 卖出  2:买入
  // * page: 
  // refresh 是否是刷新
  getZongOrderList: function (orderType, page, num, refresh) {
    var that = this;
    var params = {
      "ac": "getzongorder",
      "publickey": util.publiccode,
      "type": orderType,
      "page": page,
      "num": num,
      "tc": that.data.tc
    };
    if (!num) {
      num = 20;
    }
    if (orderType == 2) {//买入
      params.uid = that.data.uid;
    }
    console.log("orders params:", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log(responseData);
        if (!responseData.data.msg) {
          console.log(responseData.data);
          //买入
          var result = responseData.data;
          if (!refresh && that.data.buy_orders.length > 0) {
            result = that.data.buy_orders.concat(responseData.data);
          }
          for(var i=0 ;i<result.length;i++){

            // result[i].cartinfoObj = JSON.parse(result[i].cartinfo)

          }
          console.log('result:',result)
          that.setData({
            buy_orders: result
          });

        } else {
          //买入
          buy_hasMore = false;
          if (that.data.buy_orders.length <= 0) {
            that.setData({
              hasBuyData: false
            });
          }

        }
        //买入
        buy_loadingMore = false;

        wx.hideLoading();
      }
    });
  },

  
  repayOldOrder: function(event){
    var that = this;
    var order = event.currentTarget.dataset.order;
    var orderid = order.out_trade_no;
    var privatekey = utilMd5.hexMD5(this.data.uid + 'zongoldpay' + this.data.token);
    
    var data = {
      'ac': 'zongoldpay',
      'orderid': orderid,
      'binduid': util.orgid,
      'uid': this.data.uid,
      'privatekey': privatekey
    };
    console.log("支付老订单参数：", data);
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;

        console.log("支付老订单返回：", data);
        if (data.res === true) {
            //挂起微信支付请求
            var orderData = data.data;
            wx.requestPayment({

              'timeStamp': orderData.timeStamp,
              'nonceStr': orderData.nonceStr,
              'package': orderData.package,
              'signType': orderData.signType,
              'paySign': orderData.paySign,
              'success': function (res) {
                app.dialog('支付成功', 'success', function () {
                  //刷新
                  var orders = that.data.buy_orders;
                  for (var i = 0; i < orders.length; i++) {
                    var itemJo = orders[i];
                    if (order.out_trade_no == itemJo.out_trade_no) {
                      orders[i].status = 1;
                        that.setData({
                          buy_orders: orders
                        });
                      break;
                    }
                  }
                });
                if (parseInt(orderData.add_source) > 0){
                  var toice1 = tc == 1 ? '恭喜妳獲得' : '恭喜你获得';
                  var toice2 = tc == 1 ? '積分' : '积分';
                  var toice = toice1 + orderData.add_source + toice2;
                  wx.showModal({
                    title: '支付成功',
                    content: toice,
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {

                      }
                    }
                  })
                }
              },
              'fail': function (res) {
                console.log(res);
                if (res.errMsg == 'requestPayment:fail cancel') {

                } else {
                  app.dialog(res.errMsg, 'loading');
                }
              }
            });
          
        } else {
          app.dialog('购买失败', 'loading');
        }
      }
    });
  },


  //取消订单
  cancelorder: function (event) {
    var that = this;
    var order = event.currentTarget.dataset.order;
    console.log(order);
    var privatekey = utilMd5.hexMD5(this.data.uid + 'cancelgoodsorder' + this.data.token);
    var data = {
      publickey: util.publiccode,
      ac: "cancelgoodsorder",
      reason: '默认取消',
      orderid: order.orderid,
      uid: this.data.uid,
      privatekey: privatekey
    };
    
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("取消订单：",data);
        if (data.res) {
          //刷新
          var orders = that.data.buy_orders;
          
          for(var i = 0; i < orders.length; i++){
            var itemJo = orders[i];
            if (order.orderid == itemJo.orderid){
              orders[i].status = -1;
              
                that.setData({
                  buy_orders: orders
                });
              
              break;
            }
          }
        } else {
          app.dialog(data.msg, 'loading');
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(!reload){
      if(!this.data.uid){
        //当前登录用户信息
        app.getLoginUserInfo(function (res) {
          if (res == -1) {//用户拒绝授权
            return;
          }
          //更新数据
          that.setData({
            uid: res.uid,
            token: res.token,
            openid: res.openid
          });
          that.getZongOrderList(2, 1, 20, true);
        });
      } else {
        var buy_len = this.data.buy_orders.length;
        buy_len = buy_len > 0 ? buy_len : 20;
        this.getZongOrderList(2, 1, buy_len, true);
      }
    }
    reload = false;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      path = path.slice(6);
    }
    if (path) {
      wx.reLaunch({
        url: path,
      })
    }
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },
  updateAttr: function (event){
    console.log("updateAttr", event.currentTarget.dataset);
    var that = this;
    var orderid = event.currentTarget.dataset.orderid;
    var fendanid = event.currentTarget.dataset.fendanid;

    var addAttr={ groupId: "0", groupName: "房号", attributeId: "", attributeName: "888" }
    var attribute = [];
    attribute = event.currentTarget.dataset.attr || [];

    for (var i = 0; i < attribute.length; i++) {
      if (attribute[i].groupName == "房号") {
        attribute.splice(i, 1);
        i--;
      }
    }
    attribute.push(addAttr);
    console.log("attribute房号", attribute);
    var privatekey = utilMd5.hexMD5(this.data.uid + 'hotelupdateorder' + this.data.token);
    var data = {
      publickey: util.publiccode,
      ac: "hotelupdateorder",
      orderid: orderid,
      fendanid: fendanid,
      uid: this.data.uid,
      goods_attribute: JSON.stringify(attribute),
      privatekey: privatekey
    };

    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("更新订单：", data);
        if (data.res) {
          that.getZongOrderList(2, 1, 20, true);
        } else {
          app.dialog(data.msg, 'loading');
        }
      }
    });

  }
})